var UniquePasswordBuilder = (function() {

    // Include Chris Veness's SHA1 library into an object
    // From http://www.movable-type.co.uk/scripts/sha1.html
    function Sha1() {}

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
    /*  SHA-1 implementation in JavaScript (c) Chris Veness 2002-2009                                 */
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
    Sha1.prototype = {
        sha1Hash: function(msg) {
            // constants [§4.2.1]
            var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];

            // PREPROCESSING 

            msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]

            // convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
            var l = msg.length/4 + 2;  // length (in 32-bit integers) of msg + 1 + appended length
            var N = Math.ceil(l/16);   // number of 16-integer-blocks required to hold 'l' ints
            var M = new Array(N);
            for (var i=0; i<N; i++) {
                M[i] = new Array(16);
                for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
                    M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) | 
                        (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
                }
            }
            // add length (in bits) into final pair of 32-bit integers (big-endian) [5.1.1]
            // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
            // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
            M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14])
                M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

            // set initial hash value [§5.3.1]
            var H0 = 0x67452301;
            var H1 = 0xefcdab89;
            var H2 = 0x98badcfe;
            var H3 = 0x10325476;
            var H4 = 0xc3d2e1f0;

            // HASH COMPUTATION [§6.1.2]

            var W = new Array(80); var a, b, c, d, e;
            for (var i=0; i<N; i++) {

                // 1 - prepare message schedule 'W'
                for (var t=0;  t<16; t++) W[t] = M[i][t];
                for (var t=16; t<80; t++) W[t] = this.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

                // 2 - initialise five working variables a, b, c, d, e with previous hash value
                a = H0; b = H1; c = H2; d = H3; e = H4;

                // 3 - main loop
                for (var t=0; t<80; t++) {
                    var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
                    var T = (this.ROTL(a,5) + this.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
                    e = d;
                    d = c;
                    c = this.ROTL(b, 30);
                    b = a;
                    a = T;
                }

                // 4 - compute the new intermediate hash value
                H0 = (H0+a) & 0xffffffff;  // note 'addition modulo 2^32'
                H1 = (H1+b) & 0xffffffff; 
                H2 = (H2+c) & 0xffffffff; 
                H3 = (H3+d) & 0xffffffff; 
                H4 = (H4+e) & 0xffffffff;
            }

            return this.toHexStr(H0) + this.toHexStr(H1) + this.toHexStr(H2) + this.toHexStr(H3) + this.toHexStr(H4);
        },

        //
        // function 'f' [§4.1.1]
        //
        f: function (s, x, y, z) {
            switch (s) {
                case 0: return (x & y) ^ (~x & z);           // Ch()
                case 1: return x ^ y ^ z;                    // Parity()
                case 2: return (x & y) ^ (x & z) ^ (y & z);  // Maj()
                case 3: return x ^ y ^ z;                    // Parity()
            }
        },

        //
        // rotate left (circular left shift) value x by n positions [§3.2.5]
        //
        ROTL: function (x, n) {
            return (x<<n) | (x>>>(32-n));
        },

        //
        // extend Number class with a tailored hex-string method 
        //   (note toString(16) is implementation-dependant, and 
        //   in IE returns signed numbers when used on full words)
        //
        toHexStr: function(number) {
            var s="", v;
            for (var i=7; i>=0; i--) { v = (number>>>(i*4)) & 0xf; s += v.toString(16); }
            return s;
        }
        /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
    };

    // UniquePasswordBuilder

    function UniquePasswordBuilder(location, rounds) {
        _sha1 = new Sha1();
        _host = location.protocol + '//' + location.host;
        _rounds = rounds || 1;
    }

    UniquePasswordBuilder.prototype = {

        insertGenerateActions: function() {
            // cleanup : remove previous link
            var allPreviousLinks = document.querySelectorAll('a.uniquePasswordBuilder');
            for(var i = 0; i < allPreviousLinks.length; i++) {
                var previousLink = allPreviousLinks[i];
                if (previousLink.parentNode) {
                    previousLink.parentNode.removeChild(previousLink);
                }
            }

            var allPasswordInputs = document.querySelectorAll('input[type=password]');
            for(var i = 0; i < allPasswordInputs.length; i++) {
                var passwordInput = allPasswordInputs[i];
                link = document.createElement("a");
                link.setAttribute('class', 'uniquePasswordBuilder');
                link.setAttribute('style', 'padding:5px;cursor:pointer;');
                link.appendChild(document.createTextNode("generate password"));
                this.addLinkAction(link, passwordInput);
                passwordInput.parentNode.insertBefore(link, passwordInput.nextSibling);
            }
        },

        addLinkAction: function(link, passwordInput) {
            var that = this;
            var generateHandler = function(evt) {
                var currentPassword = passwordInput.value;
                var generatedPassword = that.generateUniquePassword(currentPassword);
                passwordInput.value = generatedPassword;
                var e = evt || window.event;
                e.cancelBubble = true;
                if (e.stopPropagation) e.stopPropagation();
            };
            if (link.addEventListener)
                link.addEventListener('click', generateHandler, false);
            else if (link.attachEvent)
                link.attachEvent('onclick', generateHandler);
        },

        generateUniquePassword: function(masterPassword) {
            var outputPassword = masterPassword;
            for (var i = 0; i < _rounds; i++) {
                var hashedPassword = _sha1.sha1Hash(_sha1.sha1Hash(outputPassword) + _sha1.sha1Hash(_host));
                outputPassword = this.makeHashHumanReadable(hashedPassword);
            }
            var roundsMessage = (_rounds > 1) ? ' (in ' + _rounds + ' rounds)' : '';
            console.log('UniquePasswordBuilder - Generated password: ' + outputPassword + ' for domain: ' + _host + roundsMessage);
            return outputPassword;
        },

        makeHashHumanReadable: function(hash) {
            var availableChars = [ '!','$','+','-','.',':',';','?','0','1','2','3','4','5','6','7','8','9','0',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' ];

            var password = '';
            for(i = 0; i < hash.length; i+=4) {
                var v = hash.substr(i, 4);
                var n = Number('0x' + v);
                password += availableChars[n % availableChars.length];
            }
            return password;
        }
    };

    var blockAutoLaunch = window.uniquePasswordBuilderBlockAutoLaunch === true;
    if (!blockAutoLaunch) {
        var u = new UniquePasswordBuilder(window.location, window.uniquePasswordBuilderRounds);
        u.insertGenerateActions();
    }

    return {
        UniquePasswordBuilder: UniquePasswordBuilder,
        Sha1: Sha1
    };
})();
